import { useEffect, useState } from "react";
import { useModel } from "umi";
import { FindAllMembers } from "../../_graphql/member";
import { Form, Table, Button, Checkbox, Upload, message, Space } from "antd";

const AddRoleMembersModal = ({ role, members, reloadData }) => {
    const { graphqlFetch } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [newMembers, setNewMembers] = useState([]);
    const [selectedMembers, setSelectedMembers] = useState([]);

    const loadNewMembers = async () => {
        let res = await graphqlFetch({ query: FindAllMembers, variables: {} });
        if (res) {
            const allMembers = res?.a?.nodes || [];
            setNewMembers(allMembers.filter((item) => members.findIndex((_item) => _item.member.omUuid === item.omUuid) === -1));
        }
    };

    useEffect(() => {
        loadNewMembers();
    }, []);

    const addRoleMembers = async () => {
        if (selectedMembers.length === 0) return;
        let graphql = "";

        for (let index = 0; index < selectedMembers.length; index++) {
            const member = newMembers.find((item) => item.omUuid === selectedMembers[index]);
            graphql += `${"a" + index}: createApplicationRolesMember(input: { applicationRolesMember: { arUuid: "${role.arUuid}", omUuid: "${member.omUuid}" }})
            { clientMutationId }`;
        }

        let res = await graphqlFetch({ query: `mutation MyMutation { ${graphql} }`, variables: {} });
        if (res) {
            message.success("成功添加角色成员");
            await reloadData(role);
            onCloseGlobalModal();
        }
    };

    return (
        <div>
            <Checkbox.Group
                options={newMembers.map((item) => ({
                    label: item.omName + `(${item.omIfim ? "内部成员" : "外部成员"})`,
                    value: item.omUuid,
                }))}
                onChange={(keys) => setSelectedMembers(keys)}
            />

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Button type="primary" disabled={selectedMembers.length === 0} onClick={addRoleMembers}>
                    添加成员
                </Button>
            </div>
        </div>
    );
};

export default AddRoleMembersModal;
